package com.acargil.sudoku.model.exception;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import com.acargil.sudoku.model.structure.Coordinate;

public class SudokuValidationException extends Exception {

	private static final long serialVersionUID = 1L;

	private List<Coordinate> coordinates;
	
	public SudokuValidationException(String msg) {
		super(msg);
		coordinates = new ArrayList<Coordinate>();
	}

	public SudokuValidationException(String msg, List<Coordinate> coordinates) {
		this(msg);
		addCoordinates(coordinates);
	}

	public String getDetailedMessage() {
		StringBuffer buffer = new StringBuffer();
		buffer.append(super.getMessage());
		if (coordinates != null && coordinates.size() > 0) {
			buffer.append(" Coordinates: ");
			for (Coordinate coordinate : coordinates) {
				buffer.append(coordinate + " ");
			}
		}
		
		return buffer.toString();
	}
	
	public List<Coordinate> getCoordinates() {
		return coordinates;
	}
	
	public void addCoordinates(Collection<Coordinate> coordinates) {
		if (coordinates != null) {
			this.coordinates.addAll(coordinates);
		}
	}

	public static SudokuValidationException create(SudokuValidationException existingException, SudokuValidationException newException) {
		if (existingException != null) {
			StringBuilder stringBuilder = new StringBuilder(existingException.getMessage());
			stringBuilder.append("\n");
			stringBuilder.append(newException.getMessage());
			
			List<Coordinate> existingCoordinates = existingException.getCoordinates();
			existingCoordinates.addAll(newException.getCoordinates());
			
			return new SudokuValidationException(stringBuilder.toString(), existingCoordinates);
		}
		else {
			return newException;
		}
	}
	
}
